package com.iie.bigVideo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.iie.bigVideo.entity.*;
import com.iie.bigVideo.entity.dto.AnnexDto;
import com.iie.bigVideo.entity.dto.CatalogDto;
import com.iie.bigVideo.entity.dto.UserDto;
import com.iie.bigVideo.mapper.*;
import com.iie.bigVideo.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iie.bigVideo.utils.MD5Utils;
import com.iie.bigVideo.utils.PageUtils;
import com.iie.bigVideo.utils.ResultUtils;
import com.iie.bigVideo.vo.ResultVO;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author XXX
 * @since 2023-11-20
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CatalogMapper catalogMapper;
    @Autowired
    private UserCatalogMapper userCatalogMapper;
    @Autowired
    private VideoMapper videoMapper;
    @Autowired
    private AnnexImgMapper annexImgMapper;

    /**
     * 查询普通用户
     *
     * @return
     */
    @Override
    public ResultVO queryUserList(int current, int size, User user) {
        if (current <= 0 || size <= 0) {
            return ResultUtils.error(400, "false", "无效参数：current 和 size 必须大于 0");
        }
        Integer count = userMapper.countUser(user);//查询普通用户个数
        if (count == null || count == 0) {
            return ResultUtils.success(new PageUtils<>()); // 如果没有记录，则无需查询
        }

        // 计算总页数
        int pageCount = (int) Math.ceil((double) count / size);

        // 计算当前页的起始索引
        int start = (current - 1) * size;

        // 查询数据库获取当前页的数据
        List<UserDto> userListPage = userMapper.queryUserListPage(start, size, user);
//        List<UserDto> newUserListPage = new ArrayList<>();
//        for (int i = 0; i < userListPage.size(); i++) {
//            String password = MD5Utils.decodeBase64(userListPage.get(i).getUserPassword());
//            userListPage.get(i).setUserPassword(password);
//            newUserListPage.add(userListPage.get(i));//添加到新的集合里
//        }
        // 创建并填充 PageUtils 对象
        PageUtils<UserDto> userPageUtils = new PageUtils<>();
        userPageUtils.setCount(count);
        userPageUtils.setPageCount(pageCount);
        userPageUtils.setList(userListPage);

        return ResultUtils.success(userPageUtils);
    }

    /**
     * 添加普通用户
     *
     * @param user
     * @return
     */
    @Override
    public ResultVO addUser(User user) {
        if (user == null) {
            return ResultUtils.error(500, "false", "服务器异常！");
        }
        User userByUserName = userMapper.queryUserByUserName(user.getUserName());
        if (userByUserName != null) {
            return ResultUtils.error(201, "false", "用户名已存在！");
        }
//        user.setUserPassword(user.getUserPassword());
        user.setUserIsDeleted(0);//逻辑删除默认为0
        user.setUserCreatedTime(new Date());
        user.setUserUpdatedTime(new Date());
        userMapper.addUser(user);//新增
        User userObject = userMapper.queryUser(user.getUserId());
        if (userObject == null) {
            return ResultUtils.error(201, "false", "用户添加失败！");
        }
        //添加中间表  目录，时间 & 目录，时间
        if (user.getCatalogId() != null && !user.getCatalogId().isEmpty()) {
            //普通用户新增成功，目录ID不是空
            List<UserCatalog> userCatalogArrayList = new ArrayList<>();
            String[] split = user.getCatalogId().split("&");
            //对中间表进行赋值
            for (String s : split) {
                UserCatalog userCatalog = new UserCatalog();
                userCatalog.setUserId(userObject.getUserId());//新增完的普通用户id
                String[] catalogIdWithAssert = s.split(",");
                userCatalog.setCatalogId(Integer.parseInt(catalogIdWithAssert[0]));//目录ID
                userCatalog.setUserCatalogAssert(catalogIdWithAssert[1]);//绑定的时间
                userCatalogArrayList.add(userCatalog);//添加到集合中
            }
            userCatalogMapper.addUserCatalog(userCatalogArrayList);//新增中间表数据
        }
        return ResultUtils.success(userObject);
    }

    /**
     * 修改普通用户信息
     *
     * @param user
     * @return
     */
    @Override
    public ResultVO updateUser(User user) {
        if (user == null) {
            return ResultUtils.error(500, "false", "服务器异常！");
        }
//        user.setUserPassword(user.getUserPassword());
        user.setUserUpdatedTime(new Date());
        Boolean updateByUserId = userMapper.updateByUserId(user);
        if (!updateByUserId) {
            return ResultUtils.error(201, "false", "用户修改失败！");
        }
        if (user.getCatalogId() != null && !user.getCatalogId().isEmpty()) {
            //不为空就开始修改 中间表内容
            List<UserCatalog> userCatalogArrayList = new ArrayList<>();
            String[] split = user.getCatalogId().split("&");
            //对中间表进行赋值 目录，时间 & 目录，时间
            for (String s : split) {
                UserCatalog userCatalog = new UserCatalog();
                userCatalog.setUserId(user.getUserId());//新增完的普通用户id
                String[] catalogIdWithAssert = s.split(",");
                userCatalog.setCatalogId(Integer.parseInt(catalogIdWithAssert[0]));//目录ID
                userCatalog.setUserCatalogAssert(catalogIdWithAssert[1]);//绑定的时间
                userCatalogArrayList.add(userCatalog);//添加到集合中
            }
            Integer userCatalog = userCatalogMapper.queryUserCatalogByUserId(String.valueOf(user.getUserId()));
            if (userCatalog > 0) {
                Integer integer = userCatalogMapper.deleteUserCatalog(String.valueOf(user.getUserId()));//对符合的用户ID 进行删除。
                if (integer <= 0) {
                    return ResultUtils.error(500, "false", "服务器异常！");
                }
            }
            userCatalogMapper.addUserCatalog(userCatalogArrayList);//新增中间表数据
        } else {
            //没有的情况下
            Integer userCatalog = userCatalogMapper.queryUserCatalogByUserId(String.valueOf(user.getUserId()));
            if (userCatalog > 0) {
                Integer integer = userCatalogMapper.deleteUserCatalog(String.valueOf(user.getUserId()));//对符合的用户ID 进行删除。
            }
        }
        return ResultUtils.success(updateByUserId);
    }

    /**
     * 修改普通用户状态
     *
     * @param id
     * @param isDelete
     * @return
     */
    @Override
    public ResultVO updateStateByUserID(int id, int isDelete) {
        Boolean aBoolean = userMapper.updateStateByUserID(id, isDelete);
        return ResultUtils.success(aBoolean);
    }


    /**
     * 删除普通用户信息
     *
     * @param id
     * @return
     */
    @Override
    public ResultVO deleteUser(int id) {
        Integer deleteByUser = userMapper.deleteByUserID(id);
        if (deleteByUser > 0) {
            //删除成功，进行删除中间表
            userCatalogMapper.deleteUserCatalog(String.valueOf(id));
        }
        return ResultUtils.success(deleteByUser);
    }

    /**
     * 普通用户登录
     *
     * @param username 用户名
     * @param password 密码
     * @return
     */
    @Override
    public ResultVO<UserDto> login(String username, String password) {
        if (!StringUtils.isAnyBlank(username) && !StringUtils.isAnyBlank(password)) {
            //说明不为空
            UserDto userObject = userMapper.userLogin(username);//单个用户的
            if (userObject == null) {
                //说明没此用户
                return ResultUtils.error(201, "false", "登录失败，用户名不存在！");
            } else {
                //说明有此用户，开始校验密码是否正确 和 是否被禁用
                if (userObject.getUserIsDeleted() == 1) {
                    return ResultUtils.error(201, "false", "用户已被禁用，请联系管理员！");
                } else {
                    // 开始校验是不是在当前日期有效范围内
                    // 获取当前日期
                    LocalDate currentDate = LocalDate.now();
                    String[] dateRange = userObject.getUserAssert().split("~");
                    // 指定日期范围
                    LocalDate startDate = LocalDate.parse(dateRange[0]);
                    LocalDate endDate = LocalDate.parse(dateRange[1]);
                    // 判断当前日期是否在指定范围内
                    if (currentDate.isBefore(startDate) || currentDate.isAfter(endDate)) {
                        //解析：开始时间 是否在 当前时间之前？  结束时间 是否在 当前时间 之后？
                        return ResultUtils.error(201, "false", "用户没在使用时间范围内，请联系管理员！");
                    } else {
                        if (password.equals(userObject.getUserPassword())) {
                            //说明密码正确 并处理 返回结果
                            return ResultUtils.success(userDtoObj(userObject));
                        } else {
                            return ResultUtils.error(201, "false", "登录失败，密码错误！");
                        }
                    }
                }


            }
        }
        return ResultUtils.error(500, "false", "服务器异常！");
    }

    /**
     * 处理返回结果
     *
     * @param userDto
     * @return
     */
    private UserDto userDtoObj(UserDto userDto) {
        List<CatalogDto> catalogList = userDto.getCatalogList();
        if (catalogList.size() > 0) {
            //册
            for (CatalogDto catalogDto : catalogList) {
                if (catalogDto.getCatalogList().size() > 0) {
                    //课件
                    for (CatalogDto dto : catalogDto.getCatalogList()) {
                        if (dto.getAnnexList().size() > 0) {
                            //附件
                            for (AnnexDto annex : dto.getAnnexList()) {
                                ArrayList<String> imageId = new ArrayList<>();
                                //图集
                                imageId.add(Integer.toString(annex.getId()));
                                if (imageId.size() > 0) {
                                    ArrayList<Image> imageArrayList = new ArrayList<>();
                                    //有图集
                                    List<Image> imageList = annexImgMapper.queryByAnnexIdList(imageId);
                                    if (!imageList.isEmpty()) {
                                        for (Image image : imageList) {
                                            if (StringUtils.isNotBlank(image.getImageMainImg())) {
                                                //有封面
                                                imageArrayList.add(image);
                                            }
                                            imageArrayList.add(image);
                                        }
                                    }
                                    annex.setImageList(imageArrayList);
                                }
                            }

                        }
                    }
                }

            }
        }
        return userDto;
    }


}
